package cn.ug.pay.web.job;

import cn.ug.bean.base.SerializeObject;
import cn.ug.config.RedisGlobalLock;
import cn.ug.feign.PriceService;
import cn.ug.pay.mapper.entity.PayGoldStock;
import cn.ug.pay.service.MemberGoldService;
import cn.ug.pay.service.PayGoldStockService;
import cn.ug.util.UF;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

@Component
public class PayGoldStockJobs {
    private Log log = LogFactory.getLog(PayGoldStockJobs.class);
    @Autowired
    private MemberGoldService memberGoldService;
    @Autowired
    private PayGoldStockService payGoldStockService;
    @Autowired
    private RedisGlobalLock redisGlobalLock;
    @Autowired
    private PriceService priceService;
    private static final long EXPIRE_DAY = 1;

    @Scheduled(cron = "0/10 50 23 * * ?")
    //@Scheduled(cron = "0 33 9 * * ?")
    public void calculate() {
        String key = "Pay:PayGoldStockJobs:calculate:" + UF.getFormatDateNow();
        if(!redisGlobalLock.lock(key, EXPIRE_DAY, TimeUnit.DAYS)) {
            return;
        }
        PayGoldStock payGoldStock = memberGoldService.selectEverydayTotalGramRecord();
        if (payGoldStock != null) {
            payGoldStock.setCalculationDate(UF.getFormatDateNow());
            payGoldStockService.save(payGoldStock);
        }
    }

    @Scheduled(cron = "0/10 40 2 * * ?")
    //@Scheduled(cron = "0 23 18 * * ?")
    public void addClosingPrice() {
        String someday = UF.getFormatDateNow()+" 02:30";
        SerializeObject<Double> result = priceService.getSomedayPrice(someday);
        if (result != null) {
            double price = result.getData();
            LocalDateTime now = LocalDateTime.now();
            now = now.plusDays(-1);
            payGoldStockService.modify( UF.getFormatDate(now), new BigDecimal(price));
        }
    }
}
